package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Domain;
import server.PutCache;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import data.Data;

@SuppressWarnings("serial")
public class WhoisViewServlet extends HttpServlet {
	@SuppressWarnings("static-access")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");

		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = Utils.fomatDomain(URLDecoder.decode(st.nextToken(),"UTF-8"));
		
		if(Utils.checkDomain(name))
		{
			PersistenceManager psm = Data.get().getPersistenceManager();
			Key k = KeyFactory.createKey(Domain.class.getSimpleName(), name);
			
			PutCache putCache = new PutCache();
			Domain domain = new Domain();
			domain.setName(name);
	        try {
	        	domain = psm.getObjectById(Domain.class, k);	        	
	        	
			} catch (JDOObjectNotFoundException e) {
				new Insert(domain);
				
				putCache.putCacheDomain(domain,"lastupdates");
			}

			putCache.putCacheList(name, "siteview");
			
        	req.setAttribute("domain", domain);
        	try {
				req.getRequestDispatcher("/whois.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			resp.sendError(resp.SC_NOT_FOUND,"Link error !");
		}
		
	}
}
